//
//  HNStudentSignVC.m
//  优学荟管理系统
//
//  Created by edz on 2017/12/6.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HNStudentSignVC.h"
#import "HNStudentSignCell.h"
#import "HNStudentSignModel.h"
#import "UploadSignInPictureView.h"
#import "CourseAddStudentVC.h"
#import "ZYSignInController.h"


#define KIsiPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)

@interface HNStudentSignVC () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
{
    __weak IBOutlet UICollectionView *_CollectionView;
    __weak IBOutlet UICollectionViewFlowLayout *_CollectionViewFlow;
    __weak IBOutlet UILabel *_SelectedNum; // 选中数量
    __weak IBOutlet UIButton *_Select; // 全选按钮
    
    __weak IBOutlet UIButton *_QueQin; // 缺勤按钮
    __weak IBOutlet UIButton *_QingJia; // 请假按钮
    __weak IBOutlet UIButton *_QianDao; // 签到按钮
    __weak IBOutlet UIButton *_Add; // 新增学生
    __weak IBOutlet NSLayoutConstraint *_NavigationBarTop;
}
@property (nonatomic, strong) NSMutableArray *DataArr;

@end

@implementation HNStudentSignVC

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    // 适配iPhoneX
    _NavigationBarTop.constant += KIsiPhoneX ? 30:0;
    
    // 老师帐号没有新增学生功能
    [_Add setHidden:self.IsTeacher];
    
    [_CollectionView registerNib:[UINib nibWithNibName:[HNStudentSignCell description] bundle:nil] forCellWithReuseIdentifier:@"Cell"];
    
    // 最小item间距
    _CollectionViewFlow.minimumInteritemSpacing = 15.f;
    // 最小行之间距
    _CollectionViewFlow.minimumLineSpacing = 16.f;
    // 缩进
    _CollectionViewFlow.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15);
    
    
    
    _CollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        _SelectedNum.text = @"0";
        _Select.selected = NO;
        [self RefreshData];
    }];
    
    [_CollectionView.mj_header beginRefreshing];
}


/**
 本页数据请求
 */
- (void)RefreshData
{
    //金牌课程 点进去 详情
    ///http://192.168.0.113:8080/StarShine/ys/yxhUser.do?action=getCourseRecordNew&teacherId=361044&lessonId=8571&pageNumber=1
    NSMutableDictionary *Dict = [NSMutableDictionary dictionary];
    [Dict setValue:self.ID forKey:@"lessonId"];
    [Dict setValue:self.IsTeacher ? @"getCourseRecord2":@"getCourseRecordNew" forKey:@"action"];
    [Dict setValue:@1 forKey:@"pageNumber"];
    [Dict setValue:[AccountTool shareAccountTool].currentAccount.oid forKey:@"oid"];
    
    if (!self.IsTeacher) {
    [Dict setValue:self.teachid forKey:@"teacherId"];
    }
    
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Dict Success:^(id Obj) {
        
        [_CollectionView.mj_header endRefreshing];
        if ([Obj[@"code"] isEqualToNumber:@1000])
        {
            [self.DataArr removeAllObjects];
            // 取模型
            NSArray *Arr = Obj[@"t"][@"dataList"];
            // 转对象
            [Arr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                HNStudentSignModel *Model = [[HNStudentSignModel alloc] init_ValuForKeyWithDict:obj];
                [self.DataArr addObject:Model];
                
                // 设置底部数据
                if (idx == 0) {
                    
                    [_QueQin setTitle:[NSString stringWithFormat:@"缺勤(%@)", [Model.todayAbsence1Count stringValue]] forState:(UIControlStateNormal)];
                    [_QingJia setTitle:[NSString stringWithFormat:@"请假(%@)", [Model.todayAbsence2Count stringValue]] forState:(UIControlStateNormal)];
                    [_QianDao setTitle:[NSString stringWithFormat:@"签到(%@)", [Model.todayRecordCount stringValue]] forState:(UIControlStateNormal)];
                }
            }];
            [_CollectionView reloadData];
        }
        else
        {
            [HUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [HUD showError:NetErr];
        [_CollectionView.mj_header endRefreshing];
    }];
}


/** 请假、缺勤网络请求 status:1缺勤 2请假*/
- (void)RefreshDataForQingJiaAndQueQinOfStatus:(NSNumber *)Status andEnrollInfoId:(NSString *)EnrollInfoId {
    
    
    [MBProgressHUD showHUD];
    NSDictionary *Params = @{
                             @"action"      :@"saveAbsenteeism",
                             @"status"      :Status,
                             @"lessonId"    :[self.ID stringValue],
                             @"enrollInfoIds":EnrollInfoId
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {
        [HUD hideHUD];
        
        if ([[Obj valueForKey:@"code"] integerValue] == 1000) {
            NSArray *IDArr = [EnrollInfoId componentsSeparatedByString:@","];
            [IDArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                NSString *ID = obj;
                [self.DataArr enumerateObjectsUsingBlock:^(HNStudentSignModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    //匹配条件
                    if ([ID isEqualToString:[obj.enrollInfoId stringValue]]) {
                        
                        // 1缺勤 2请假
                        [obj SetStatus:Status];
                        obj.Selected = NO;
                        // 底部的按钮数字增加

                        NSCharacterSet *nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet];
                        NSInteger Index = [[([Status isEqualToNumber:@1] ? _QueQin:_QingJia).currentTitle stringByTrimmingCharactersInSet:nonDigits] integerValue];
                        Index = Index + 1;
                        [[Status isEqualToNumber:@1] ? _QueQin:_QingJia setTitle:[NSString stringWithFormat:@"%@(%ld)", [Status isEqualToNumber:@1] ? @"缺勤":@"请假", Index] forState:(UIControlStateNormal)];
                    }
                }];
            }];
            // 1缺勤 2请假
            [HUD showSuccess:[Status isEqualToNumber:@1] ? @"登记缺勤成功":@"登记请假成功" ];
            _SelectedNum.text = @"0";
            [_CollectionView reloadData];
            _Select.selected = NO;
            
        } else {
            [HUD hideHUD];
            [HUD showError:Obj[@"msg"]];
        }
        
        
    } Fail:^(NSError *Error) {
        [HUD hideHUD];
        [HUD showError:NetErr];
    }];
    
}



#pragma mark - CollectionView代理
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.DataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HNStudentSignModel *Model = self.DataArr[indexPath.item];
    HNStudentSignCell *Cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    Cell.Model = Model;
    Cell.Click = ^{
        // 单个选中操作
        [self ClickOneItemOfModel:Model andIndexPath:indexPath];
    };
    Cell.ClickHistory = ^(NSNumber *EnrollInfoId) {
      // 历史记录
        [self SignHistory:EnrollInfoId];
    };
    Cell.ClickDelete = ^(NSNumber *EnrollInfoId, NSNumber *ID) {
        [self deleteStudentWithID:ID errID:EnrollInfoId];
    };
    Cell.ReloadData = ^{
        [_CollectionView reloadData];
    };
    return Cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake((kScreenWidth - 60) / 3 , (kScreenWidth - 60) / 3 * 1.2);
}


#pragma mark - 删除学生
- (void)deleteStudentWithID:(NSNumber *)ID errID:(NSNumber *)errID {
//    NSString *url = [NSString stringWithFormat:@"trainLesson.do?action=delStudentNotValid&uid=%@&enrollInfoId=%@&type=1",ID,errID];

    NSString *url = @"trainLesson.do?action=delStudentNotValid";
    NSDictionary *params = @{
                             @"uid":ID,
                             @"enrollInfoId":errID,
                             @"type": @"1"
                             };
//
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];
    
    [NetManager Post:LLBaseURL(url) Auth:YES Params:params Success:^(id Obj) {
        if ([[Obj valueForKey:@"code"]integerValue] == 1000) {
            [SVProgressHUD setStatus:Obj[@"msg"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                [_CollectionView.mj_header beginRefreshing];
            });
        }
    } Fail:^(NSError *Error) {
        
        [SVProgressHUD dismiss];
    }];
}

#pragma mark - 事件
/** 全选 */
- (IBAction)ClickAllSelect:(UIButton *)Button {

    Button.selected = !Button.selected;
    // 记录选中个数
    __block NSInteger Index = 0;
    // 全选操作
    [self.DataArr enumerateObjectsUsingBlock:^(HNStudentSignModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSArray *Arr = [obj.Num componentsSeparatedByString:@"/"];
        NSInteger FirstIndex = [[Arr firstObject] integerValue];
        NSInteger LastIndex = [[Arr lastObject] integerValue];
        if (![obj.State isEqualToString:@"请假"] && ![obj.State isEqualToString:@"缺勤"] && FirstIndex != LastIndex) {
            
            obj.Selected = Button.selected;
            Index = Button.selected ? (Index + 1) : 0;
        }
    }];
    _SelectedNum.text = [@(Index) stringValue];
    
    if (Index == 0 && Button.selected == YES) {
        
        self.DataArr.count > 0 ? [MBProgressHUD showSuccess:@"所有学生已操作!"]:nil;
        Button.selected = !Button.selected;
    } else {
    
        [_CollectionView reloadData];
    }
    
    
}

/** 点击了单个item */
- (void)ClickOneItemOfModel:(HNStudentSignModel *)Model andIndexPath:(NSIndexPath *)IndexPath {
    
    Model.Selected = !Model.Selected;
    NSInteger Index = [_SelectedNum.text integerValue];
    Index = Model.Selected ? Index + 1 : Index - 1;
    _SelectedNum.text = [@(Index) stringValue];
    [_CollectionView reloadItemsAtIndexPaths:@[IndexPath]];
    // 判断是否全选
    // 记录选中个数
    __block NSInteger aIndex = 0;
    // 全选操作
    [self.DataArr enumerateObjectsUsingBlock:^(HNStudentSignModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSArray *Arr = [obj.Num componentsSeparatedByString:@"/"];
        NSInteger FirstIndex = [[Arr firstObject] integerValue];
        NSInteger LastIndex = [[Arr lastObject] integerValue];
        if (![obj.State isEqualToString:@"请假"] && ![obj.State isEqualToString:@"缺勤"] && FirstIndex != LastIndex) {
            
            aIndex =  aIndex + 1 ;
        }
    }];
    if (aIndex > 0 && aIndex == Index) {
        
        _Select.selected = YES;
    } else {
        
        _Select.selected = NO;
    }
}

/** 缺勤 */
- (IBAction)QueQing:(UIButton *)sender {
    
    if ([_SelectedNum.text integerValue] <= 0) {
        
        [MBProgressHUD showError:@"请选择需要操作的学生"];
        return;
    }
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"是否将学生设置为缺勤?" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    [Alert addAction:[UIAlertAction actionWithTitle:@"缺勤" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        
        [self RefreshDataForQingJiaAndQueQinOfStatus:@1 andEnrollInfoId:[self GetEnrollInfor]];
    }]];
    [Alert addAction:[UIAlertAction actionWithTitle:@"放弃" style:(UIAlertActionStyleCancel) handler:nil]];
    [self presentViewController:Alert animated:YES completion:nil];
}

/** 请假 */
- (IBAction)QingJia:(UIButton *)sender {
    
    if ([_SelectedNum.text integerValue] <= 0) {
        
        [MBProgressHUD showError:@"请选择需要操作的学生"];
        return;
    }
    
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"是否将学生设置为请假?" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    [Alert addAction:[UIAlertAction actionWithTitle:@"请假" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        [self RefreshDataForQingJiaAndQueQinOfStatus:@2 andEnrollInfoId:[self GetEnrollInfor]];
    }]];
    [Alert addAction:[UIAlertAction actionWithTitle:@"放弃" style:(UIAlertActionStyleCancel) handler:nil]];
    [self presentViewController:Alert animated:YES completion:nil];
}

/** 签到 */
- (IBAction)QianDao:(UIButton *)sender {
    
    if ([_SelectedNum.text integerValue] <= 0) {
        
        [MBProgressHUD showError:@"请选择需要操作的学生"];
        return;
    }
    // 提交相片及数据
    [UploadSignInPictureView UploadSignInPictureView_ConfigViewWithLessonId:[self.ID stringValue] Uids:[self GetUids] enrollInfoIds:[self GetEnrollInfor] Complete:^{
        //签到成功
        NSArray *IDArr = [[self GetEnrollInfor] componentsSeparatedByString:@","];
        [IDArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSString *ID = obj;
            [self.DataArr enumerateObjectsUsingBlock:^(HNStudentSignModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                //匹配条件
                if ([ID isEqualToString:[obj.enrollInfoId stringValue]]) {
                    
                    [obj SetStatus:@10];
                    obj.Selected = NO;
                    // 次数 +1
                    NSArray *Arr = [obj.Num componentsSeparatedByString:@"/"];
                    NSInteger FirstIndex = [[Arr firstObject] integerValue];
                    FirstIndex = FirstIndex + 1;
                    obj.Num = [NSString stringWithFormat:@"%ld/%d", (long)FirstIndex, [[Arr lastObject] integerValue]];

                }
            }];
        }];
        
        __block NSInteger Index = 0;
        [self.DataArr enumerateObjectsUsingBlock:^(HNStudentSignModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            // 底部的按钮数字增加
            if ([obj.State isEqualToString:@"到课"]) {
                Index = Index + 1;
            }
        }];
        [_QianDao setTitle:[NSString stringWithFormat:@"%@(%ld)",  @"签到", (long)Index] forState:(UIControlStateNormal)];
        // 1缺勤 2请假
        _SelectedNum.text = @"0";
        [_CollectionView reloadData];
        _Select.selected = NO;
    }];
}

/** Pop */
- (IBAction)Pop {
    
    [self.navigationController popViewControllerAnimated:YES];
}

/** 增加学生 */                              
- (IBAction)GoAddVC {
    
    //实例化增加学生VC
    CourseAddStudentVC *VC = [[CourseAddStudentVC alloc] init];
    //课程ID值传递
    VC.lessonId = [self.ID stringValue];
    //推出
    [self.navigationController pushViewController:VC animated:YES];
    // 学生增加之后刷新本界面
    VC.RefreshStudent = ^ () {
        [self.DataArr removeAllObjects];
        [_CollectionView reloadData];
        //网络请求数据
        [_CollectionView.mj_header beginRefreshing];
    };
}

/** 签到记录 */
- (void)SignHistory:(NSNumber *)EnrollInfoId {
    
    ZYSignInController *VC = [[ZYSignInController alloc] init];
    VC.ID = [EnrollInfoId stringValue];
    [self.navigationController pushViewController:VC animated:YES];
}
#pragma mark - Func
/** 获取被选中的报名ID */
- (NSString *)GetEnrollInfor {
    
    NSMutableArray *Arr = [NSMutableArray array];
    [self.DataArr enumerateObjectsUsingBlock:^(HNStudentSignModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (obj.Selected == YES) {
            
            [Arr addObject:[obj.enrollInfoId stringValue]];
        }
    }];
    return [Arr componentsJoinedByString:@","];
}

/** 获取用户的ID */
- (NSString *)GetUids {
    
    NSMutableArray *Arr = [NSMutableArray array];
    [self.DataArr enumerateObjectsUsingBlock:^(HNStudentSignModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (obj.Selected == YES) {
            
            [Arr addObject:[obj.User_ID stringValue]];
        }
    }];
    return [Arr componentsJoinedByString:@","];
}

#pragma mark - Get
- (NSMutableArray *)DataArr {
    
    if (!_DataArr) {
        
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}
@end
